package com.mi.rule.db.core;

import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.mi.rule.db.entity.MiEntity;
import org.springframework.core.annotation.AnnotationUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 强化自定义构造器
 *
 * @author 王永吉
 */
public class MiWrapper<P extends MiEntity> extends QueryWrapper<P> {

    //实现了MiEntity接口的实体列
    private Class<P> mipClass;

    //tableName=null时，表名从typeClass读取
    private String tableName = null;

    /**
     * @param mipClass 实现了MiEntity接口的实体类
     */
    public MiWrapper(Class<P> mipClass) {
        boolean assignableFrom = MiEntity.class.isAssignableFrom(mipClass);
        if (assignableFrom) {
            TableName annotation = AnnotationUtils.findAnnotation(mipClass, TableName.class);
            if (annotation != null) {
                this.tableName = annotation.value();
            }
        }
        this.mipClass = mipClass;
    }

    /**
     * 拼接 join语句
     */
    private List<String> sqlJoin = new ArrayList<>();

    public void leftJoin(String tableName, String on) {
        sqlJoin.add(" left join " + tableName + " on " + on + " ");
    }

    public void join(String tableName, String on) {
        sqlJoin.add(" join " + tableName + " on " + on + " ");
    }

    public void rightJoin(String tableName, String on) {
        sqlJoin.add(" right join " + tableName + " on " + on + " ");
    }

    public String getSqlJoin() {
        if (CollectionUtils.isEmpty(sqlJoin)) {
            return " ";
        }
        return String.join(" ", sqlJoin);
    }

    /**
     * 操作set语句
     */
    private List<String> sqlSet = new ArrayList<>();

    public MiWrapper<P> sqlSet(String column, Object val) {
        sqlSet.add(String.format("%s=%s", column, formatSql("{0}", val)));
        return this;
    }

    public MiWrapper<P> sqlSet(String sql) {
        if (StringUtils.isNotBlank(sql)) {
            sqlSet.add(sql);
        }
        return this;
    }

    public String getSqlSet() {

        if (CollectionUtils.isEmpty(sqlSet)) return null;

        return String.join(StringPool.COMMA, sqlSet);
    }

    /**
     * limit 操作
     *
     * @param limit 截取条数
     */
    public MiWrapper<P> limit(Object limit) {
        this.last("limit " + limit);
        return this;
    }

    public Class<P> tClass() {
        return mipClass;
    }

    public String getTableName() {
        return tableName;
    }

    public MiWrapper<P> setTableName(String tableName) {
        this.tableName = tableName;
        return this;
    }
}
